package com.jilian.mydemo.modul.order.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.view.WheelView;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.common.dto.ParamsDto;
import com.jilian.mydemo.common.dto.ParamsListDto;
import com.jilian.mydemo.common.dto.PathDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.order.adapter.SelectServiceWheelAdapter;
import com.jilian.mydemo.modul.order.adapter.SignUpAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.utils.DateUtil;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.Utils;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;

public class HydraulicDeclarationActivity extends BaseActivity implements CustomItemClickListener, SignUpAdapter.CloseListener, BDLocationListener {

    TimePickerView pvCustomTime;
    private EditText etName;
    private EditText etPhone;
    private EditText etAdress;
    private TextView tvStartTime;
    private TextView tvStopTime;
    private EditText etContent;
    private TextView tvOk;
    private OrderViewModel orderViewModel;
    private EditText etCode;
    private TextView tvServiceType;
    //
    private RecyclerView recyclerView;
    private SignUpAdapter adapter;
    private List<PathDto> datas;
    private GridLayoutManager gridLayoutManager;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_hydraulicdeclaration;
    }

    @Override
    public void initView() {
        setNormalTitle("水工报单", v -> finish());
        etName = (EditText) findViewById(R.id.et_name);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etAdress = (EditText) findViewById(R.id.et_adress);
        tvStartTime = (TextView) findViewById(R.id.tv_start_time);
        tvStopTime = (TextView) findViewById(R.id.tv_stop_time);
        etContent = (EditText) findViewById(R.id.et_content);
        etCode = (EditText) findViewById(R.id.et_code);
        tvServiceType = (TextView) findViewById(R.id.tv_service_type);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        initPhoto();
        initCustomTimePicker();
        reportInitParam();
    }

    /**
     * 上传图片
     */
    private void initPhoto() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, DisplayUtil.dip2px(this, 10));//下间距
        recyclerView.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        tvOk = (TextView) findViewById(R.id.tv_ok);
        gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        datas = new ArrayList<>();
        PathDto dto = new PathDto();
        dto.setType(1);
        datas.add(dto);
        adapter = new SignUpAdapter(this, datas, this, this);
        recyclerView.setAdapter(adapter);
    }

    /**
     * 水工报单下拉参数
     */
    private List<ParamsDto> serviceType;

    private void reportInitParam() {
        showLoadingDialog();
        orderViewModel.reportInitParam();
        orderViewModel.getReportParamliveData().observe(this, new Observer<BaseDto<ParamsListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<ParamsListDto> paramsListDtoBaseDto) {
                hideLoadingDialog();
                if (paramsListDtoBaseDto.isSuccess()) {
                    serviceType = paramsListDtoBaseDto.getData().getServiceType();

                } else {
                    ToastUitl.showImageToastTips(paramsListDtoBaseDto.getMsg());
                }
            }
        });
    }

    @Override
    public void initData() {
        OrderDto orderDto = (OrderDto) getIntent().getSerializableExtra("orderDto");
        if (EmptyUtils.isNotEmpty(orderDto)) {
            etName.setText(orderDto.getCustomerName());
            etPhone.setText(orderDto.getCustomerPhone());
            etAdress.setText(orderDto.getServiceAddress());
        }
    }

    private int dateType;//1 开始时间 2 结束时间 3 预约时间

    @Override
    public void initListener() {
        tvServiceType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmptyUtils.isNotEmpty(serviceType)) {
                    return;
                }
                showDialog(serviceType);
            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonEnable();
            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonEnable();
            }
        });
        etAdress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonEnable();
            }
        });
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateButtonEnable();
            }
        });


        tvStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dateType = 1;
                pvCustomTime.show();
            }
        });
        tvStopTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dateType = 2;
                pvCustomTime.show();
            }
        });
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.checkPhoneNo(etPhone.getText().toString())) {
                    ToastUitl.showImageToastTips("请输入正确的手机号码");
                    return;
                }
                try {
                    long startTime = DateUtil.stringToDate("yyyy-MM-dd HH:mm", tvStartTime.getText().toString()).getTime();
                    long stopTime = DateUtil.stringToDate("yyyy-MM-dd HH:mm", tvStopTime.getText().toString()).getTime();
                    if (startTime >= stopTime) {
                        ToastUitl.showImageToastTips("结束时间要大于开始时间");
                        return;
                    }
                    reportOrder();
                } catch (ParseException e) {
                    e.printStackTrace();
                }


            }
        });
    }

    /**
     * 报单
     */
    private void reportOrder() {
        showLoadingDialog();

        orderViewModel.reportOrder(etName.getText().toString(),
                etPhone.getText().toString(),
                etAdress.getText().toString(),
                tvStartTime.getText().toString(),
                tvStopTime.getText().toString(),
                etContent.getText().toString(), etCode.getText().toString(), code, getIntent().getStringExtra("orderId"), getFiles());
        orderViewModel.getReportliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto dto) {
                hideLoadingDialog();
                if (dto.isSuccess()) {
                    ToastUitl.showImageToastSuccess("报单成功");
                    finish();
                } else {
                    ToastUitl.showImageToastTips(dto.getMsg());
                }
            }
        });
    }

    /**
     * 更新按钮状态
     */
    private void updateButtonEnable() {
        if (TextUtils.isEmpty(etName.getText().toString())
                || TextUtils.isEmpty(etPhone.getText().toString())
                ||
                TextUtils.isEmpty(etAdress.getText().toString())
                ||
                TextUtils.isEmpty(tvStartTime.getText().toString())
                ||
                TextUtils.isEmpty(tvStopTime.getText().toString())
                || TextUtils.isEmpty(etCode.getText().toString())
                || TextUtils.isEmpty(tvServiceType.getText().toString())) {
            tvOk.setEnabled(false);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_dark);

        } else {
            tvOk.setEnabled(true);
            tvOk.setBackgroundResource(R.drawable.shape_btn_login_normal);
        }
    }

    /**
     * 初始化时间数据
     */
    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1918, 1, 23);


        //设置结速时间
        Calendar endDate = Calendar.getInstance();
        endDate.set(2030, 1, 23);

        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                if (dateType == 1) {
                    tvStartTime.setText(DateUtil.dateToString(DateUtil.DEFAULT_DATE_FORMATTER_HOUR, date) + ":00");
                    updateButtonEnable();
                }
                if (dateType == 2) {
                    tvStopTime.setText(DateUtil.dateToString(DateUtil.DEFAULT_DATE_FORMATTER_HOUR, date) + ":00");
                    updateButtonEnable();
                }


            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentTextSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*.setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
                /*.animGravity(Gravity.RIGHT)// default is center*/
                .setDate(selectedDate)
                .setRangDate(selectedDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                //各个部分是否显示
                .setType(new boolean[]{true, true, true, true, false, false})
                //时间格式
                .setLabel("", "", "", ":00", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(40, 0, -40, 0, 0, -0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFe0e0e0)
                .setLineSpacingMultiplier(2f)
                .build();
    }

    private String code;

    private void showDialog(List<ParamsDto> paramsDtos) {

        NiceDialog.init()
                .setLayoutId(R.layout.dialog_select_courier)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        WheelView wheelview = (WheelView) holder.getView(R.id.wheelview);
                        wheelview.setCyclic(false);
                        TextView tvCancel = (TextView) holder.getView(R.id.tv_cancel);
                        TextView tvFinish = (TextView) holder.getView(R.id.tv_finish);

                        TextView tvTitle = (TextView) holder.getView(R.id.tv_title);
                        tvTitle.setText("请选择服务类型");
                        wheelview.setAdapter(new SelectServiceWheelAdapter(paramsDtos));
                        tvFinish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                updateButtonEnable();
                                tvServiceType.setText(paramsDtos.get(wheelview.getCurrentItem()).getValue());
                                code = paramsDtos.get(wheelview.getCurrentItem()).getCode();

                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                updateButtonEnable();
                            }
                        });
                        wheelview.setCurrentItem(0);
                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {

    }

    @Override
    public void onItemClick(View view, int position) {
        if (datas.get(position).getType() == 2) {
            //seePhoto();
        } else {
            showAddPhoto();
        }

    }

    /**
     * 添加图片
     */
    private void showAddPhoto() {
        showSelectPhotoTypeDialog();
    }

    @Override
    public void close(int position) {
        datas.remove(position);
        if (datas.get(datas.size() - 1).getType() == 2) {
            PathDto dto = new PathDto();
            dto.setType(1);
            datas.add(dto);
        }
        adapter = new SignUpAdapter(this, datas, this, this);
        recyclerView.setAdapter(adapter);

    }

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(HydraulicDeclarationActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(HydraulicDeclarationActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(HydraulicDeclarationActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(HydraulicDeclarationActivity.this, FILE_PROVIDER, 10 - datas.size(), FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    private String path;
    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    for (int i = 0; i < uriList.size(); i++) {
                        Uri uri = uriList.get(i);
                        path = SelectPhotoUtils.getRealPathFromURI(this, uri);
                        PathDto dto = new PathDto(path, 2);
                        datas.add(0, dto);
                        if (datas.size() == 10) {
                            datas.remove(datas.size() - 1);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    updateButtonEnable();
                    break;
                //相机
                case FROM_CAPTURE:
                    path = SelectPhotoUtils.capturePathResult();
                    PathDto dto = new PathDto(path, 2);
                    datas.add(0, dto);
                    if (datas.size() == 10) {
                        datas.remove(datas.size() - 1);
                    }
                    adapter.notifyDataSetChanged();
                    updateButtonEnable();
                    break;
            }

        }
    }

    /**
     * 获取需要上传的文件
     *
     * @return
     */
    private List<File> getFiles() {
        if (datas.size() == 1 && datas.get(0).getType() == 1) {
            return null;
        }
        List<File> files = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i).getType() == 2) {
                files.add(new File(datas.get(i).getUrl()));
            }

        }
        return files;
    }
}
